package com.mrjoew.weekend.web.wechat;

import com.google.common.collect.Lists;
import com.mrjoew.wechat.entities.Properties;
import com.mrjoew.wechat.entities.Signature;
import com.mrjoew.wechat.entities.xml.in.InMessage;
import com.mrjoew.wechat.utils.SHA1Util;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

/**
 * @author Christopher Jones
 * @ClassName WeChatController
 * @explain
 * @date 2019/11/26 0026 21:47
 */
@Api(tags = "微信")
@Slf4j
@EnableConfigurationProperties(Properties.class)
@RequestMapping(value = "/weChat")
@RestController
public class WeChatController {

    private final Properties properties;

    public WeChatController(Properties properties) {
        this.properties = properties;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String weChat(Signature signature, HttpServletRequest request) {
        String requestMethod = request.getMethod();

        if (requestMethod.equals(HttpMethod.GET.name())) {
            log.info("Signature: {}, Timestamp: {}, Nonce: {}",
                    signature.getSignature(), signature.getTimestamp(), signature.getNonce());

            List<String> strings = Lists.newArrayList(properties.getServer().getToken(),
                    signature.getTimestamp(), signature.getNonce());
            Collections.sort(strings);

            StringBuilder sb = new StringBuilder();
            for (String str : strings) {
                sb.append(str);
            }

            if (SHA1Util.encode(sb.toString()).equalsIgnoreCase(signature.getSignature())) {
                log.info("WeChat Validate Access!");
                return signature.getEchostr();
            } else {
                return "";
            }
        } else if (requestMethod.equals(HttpMethod.POST.name())) {

        }

        return "";
    }

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE)
    public String post(@RequestBody InMessage inMessage) {
        log.info("InMessage: {}", inMessage.getContent());
        return "";
    }
}